/*
 * Copyright © OpenAtom Foundation.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package io.iec.edp.caf.databaseobject.manager.persistent;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.iec.edp.caf.databaseobject.api.entity.AbstractDatabaseObject;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.ArrayList;

/**
 * @author zhaoleitr
 */
public class DatabaseObjectDac {
    /**
     * 新建DBO文件
     *
     * @param fullPath 全路径
     * @param object   实体
     */
    public void createDatabaseObject(String fullPath, AbstractDatabaseObject object) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String content = mapper.writeValueAsString(object);
            writeDbo(fullPath, content);
        } catch (Exception e) {
            throw new RuntimeException("新建DBO文件出错：" + e.getMessage(), e);
        }
    }

    /**
     * 更新DBO文件
     *
     * @param fullPath 全路径
     * @param object   实体
     */
    public void updateDatabaseObject(String fullPath, AbstractDatabaseObject object) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String content = mapper.writeValueAsString(object);
            writeDbo(fullPath, content);
        } catch (Exception e) {
            throw new RuntimeException("更新DBO文件出错：" + e.getMessage(), e);
        }
    }

    private void writeDbo(String fullPath, String content) {
        BufferedWriter writer = null;
        try {
            File dboFile = new File(fullPath);
            dboFile.deleteOnExit();
            dboFile.createNewFile();
            // 三、向目标文件中写入内容，BufferedWriter可以指定编码，避免安全问题
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dboFile, true), "UTF-8"));
            writer.append(content);
            writer.flush();
        } catch (Exception e) {
            throw new RuntimeException(fullPath + "文件写入内容出错:" + e.getMessage(), e);
        } finally {
            try {
                if (null != writer) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public final String read(String fullPath) {
        String fileContent = null;
        try {
            fileContent = fileRead(fullPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileContent;
    }

    public static String fileRead(String path) throws IOException {
        String encoding = "UTF-8";
        //File file = new File(path);
        File file = null;
        file = ResourceUtils.getFile(path);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];

        FileInputStream in = new FileInputStream(file);
        in.read(filecontent);
        in.close();

        //判断有没有utf-8 bom头。有则去除。
        String fileContents = new String(filecontent, encoding);
        if (fileContents.startsWith("\ufeff")) {

            fileContents = fileContents.substring(1);

        }
        return fileContents;
    }

    public final ArrayList<String> getFilePaths(String path) {
        ArrayList<String> list = new ArrayList<>();
        File[] files = new File(path).listFiles();
        for (File file : files) {
            list.add(file.getPath());
        }
        return list;
    }
}
